# -*- coding: utf-8 -*-
# @Time : 2022/7/12 10:59
# @Author : Dftre
# @Email : 3066417822@qq.com
# @File : interpolation.py
# @Project : 代码生成器
import re

from .processor import Processor, GeneratorException


class Interpolation(Processor):
    def __init__(self, val_dict: dict):
        super().__init__(r'#\{(\w+)}')
        super()._add_doc("val_dict", val_dict)
        self.val_dict = val_dict

    def sub(self, text):
        val_list = set(re.findall(self.rule, text))  # 找到所有的 #{val} 中的 val
        for val in set(val_list):
            val = re.sub(r'\s', '', val)  # 去除值的无用字符
            if val not in self.val_dict:
                raise GeneratorException('Interpolation', '不存在该变量{}'.format(val))
            else:
                text = re.sub(r'#\{' + val + '}', str(self.val_dict[val]), text)
        return text
